package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.UsersApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Users;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.Contacts;
import com.tanhua.server.vo.MessageLike;
import com.tanhua.server.vo.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author YuShiLong
 * @Date 2021/4/20 9:53
 * @Version 1.0
 */
@Service
public class IMService {

    @Reference(version = "1.0.0")
    private UsersApi usersApi;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${tanhua.sso.url}")
    private String url;

    @Autowired
    private UserInfoService userInfoService;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;


    public Boolean contactUsers(Long userId) {

        //需要做两件事,1.保存数据到MongoDB,2.好友关系注册到环信

        Users users = new Users();
        users.setUserId(UserThreadLocal.get().getId());
        users.setFriendId(userId);

        //调用dubbo提供的saveUsers服务,保存数据到MongoDB
        String id = usersApi.saveUsers(users);

        //将好友关系注册到环信
        if (StringUtils.isNotEmpty(id)) {
            String targetUrl = url + "/user/huanxin/contacts/" + users.getUserId() + "/" + users.getFriendId();
            ResponseEntity<Void> responseEntity = this.restTemplate.postForEntity(targetUrl, null, Void.class);
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                return true;
            }
        }

        return false;
    }

    public PageResult queryContactsList(Integer page, Integer pageSize, String keyword) {
        //获取当前登录的用户
        User user = UserThreadLocal.get();

        List<Users> usersList = null;

        //如果可以不为空
        if (StringUtils.isNotEmpty(keyword)) {
            //调用dubbo提供的queryAllUsersList服务,查询好友列表
            usersList = usersApi.queryAllUsersList(user.getId());
        }else {
            //调用dubbo提供的queryUsersList服务,查询好友列表
            PageInfo<Users> pageInfo = usersApi.queryUsersList(user.getId(), page, pageSize);
            usersList = pageInfo.getRecords();
        }

        List<Long> userIds = new ArrayList<>();
        //遍历,并且好友id添加进userIds中
        for (Users users : usersList) {
            userIds.add(users.getFriendId());
        }

        //查询用户(好友)的信息
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        if (StringUtils.isNotEmpty(keyword)) {
            queryWrapper.like("nick_name", keyword);
        }
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(queryWrapper);

        List<Contacts> contactsList = new ArrayList<>();

        //没有关键字
        if (StringUtils.isEmpty(keyword)) {
            for (Users users : usersList) {
                for (UserInfo userInfo : userInfoList) {
                    if (users.getFriendId().longValue() == userInfo.getId().longValue()) {
                        Contacts contacts = new Contacts();
                        contacts.setAge(userInfo.getAge());
                        contacts.setAvatar(userInfo.getLogo());
                        contacts.setGender(userInfo.getSex().name().toLowerCase());
                        contacts.setNickname(userInfo.getNickName());
                        contacts.setUserId(String.valueOf(userInfo.getUserId()));
                        contacts.setCity(StringUtils.substringBefore(userInfo.getCity(), "-"));

                        contactsList.add(contacts);

                        break;
                    }
                }
            }
        }else {
            //有关键字
            for (UserInfo userInfo : userInfoList) {
                Contacts contacts = new Contacts();
                contacts.setAge(userInfo.getAge());
                contacts.setAvatar(userInfo.getLogo());
                contacts.setGender(userInfo.getSex().name().toLowerCase());
                contacts.setNickname(userInfo.getNickName());
                contacts.setUserId(String.valueOf(userInfo.getUserId()));
                contacts.setCity(StringUtils.substringBefore(userInfo.getCity(), "-"));

                contactsList.add(contacts);
            }
        }

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPages(0);
        pageResult.setCounts(0);
        pageResult.setPagesize(pageSize);
        pageResult.setItems(contactsList);

        return pageResult;
    }

    /*public PageResult queryMessageLikeList(Integer page, Integer pageSize) {
        //获取当前用户
        User user = UserThreadLocal.get();
        //调用dubbo提供的queryCommentListByUser服务,查询用户的评论数据
        PageInfo<Comment> pageInfo = this.quanZiApi.queryCommentListByUser(user.getId(), 1, page, pageSize);

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPages(0);
        pageResult.setCounts(0);
        pageResult.setPagesize(pageSize);

        //获取评论数据集
        List<Comment> records = pageInfo.getRecords();

        //遍历records获取用户id
        List<Long> userIds = new ArrayList<>();
        for (Comment comment : records) {
            userIds.add(comment.getUserId());
        }

        //调用userInfoService提供的queryUserInfoList的方法,获取用户信息
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);

        //双层for循环,获取用户信息,封装成MessageLike,然后装到messageLikeList集合中
        List<MessageLike> messageLikeList = new ArrayList<>();
        for (Comment record : records) {
            for (UserInfo userInfo : userInfoList) {
                if(userInfo.getUserId().longValue() == record.getUserId().longValue()){

                    MessageLike messageLike = new MessageLike();
                    messageLike.setId(record.getId().toHexString());
                    messageLike.setAvatar(userInfo.getLogo());
                    messageLike.setNickname(userInfo.getNickName());
                    messageLike.setCreateDate(new DateTime(record.getCreated()).toString("yyyy-MM-dd HH:mm"));

                    messageLikeList.add(messageLike);
                    break;
                }
            }
        }

        //将messageLikeList集合装进pageResult返回数据
        pageResult.setItems(messageLikeList);
        return pageResult;
    }*/

    public PageResult queryMessageLikeList(Integer page, Integer pageSize) {
        return this.messageCommentList(1, page, pageSize);
    }

    public PageResult queryMessageCommentList(Integer page, Integer pageSize) {
        return this.messageCommentList(2, page, pageSize);
    }

    public PageResult queryMessageLoveList(Integer page, Integer pageSize) {
        return this.messageCommentList(3, page, pageSize);
    }

    private PageResult messageCommentList(Integer type, Integer page, Integer pageSize) {
        User user = UserThreadLocal.get();
        PageInfo<Comment> pageInfo = this.quanZiApi.queryCommentListByUser(user.getId(), type, page, pageSize);

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPages(0);
        pageResult.setCounts(0);
        pageResult.setPagesize(pageSize);

        List<Comment> records = pageInfo.getRecords();

        List<Long> userIds = new ArrayList<>();
        for (Comment comment : records) {
            userIds.add(comment.getUserId());
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);

        List<MessageLike> messageLikeList = new ArrayList<>();
        for (Comment record : records) {
            for (UserInfo userInfo : userInfoList) {
                if (userInfo.getUserId().longValue() == record.getUserId().longValue()) {

                    MessageLike messageLike = new MessageLike();
                    messageLike.setId(record.getId().toHexString());
                    messageLike.setAvatar(userInfo.getLogo());
                    messageLike.setNickname(userInfo.getNickName());
                    messageLike.setCreateDate(new DateTime(record.getCreated()).toString("yyyy-MM-dd HH:mm"));

                    messageLikeList.add(messageLike);
                    break;
                }
            }
        }

        pageResult.setItems(messageLikeList);
        return pageResult;
    }
}
